<template>
  <div class="app-container">
<!--现在和历史数据切换-->

      <div >
        <el-button  icon="el-icon-search" size="mini" @click="openArchiverOrder">归历史</el-button>
        <el-switch
          style="float: right; padding: 3px 0"
          v-model="showHistory"
          active-text="历史"
          inactive-text="现存"
          @change="getList">
        </el-switch>
    </div>
    <el-divider><i class="el-icon-mobile-phone"></i></el-divider>


    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-row>
        <el-col :span="8">
          <el-form-item label="商品名称" prop="goodsName">
            <el-input
              v-model="queryParams.goodsName"
              placeholder="请输入商品名称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="登陆状态" prop="loginStatus">
            <el-select v-model="queryParams.loginStatus" placeholder="请选择"  clearable >
              <el-option
                v-for="dict in dict.type.login_status"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="8">
        <el-form-item label="京东账号" prop="jdAccount">
          <el-input
            v-model="queryParams.jdAccount"
            placeholder="请输入京东账号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="闲鱼账号" prop="fishAccount">
            <el-input
              v-model="queryParams.fishAccount"
              placeholder="请输入闲鱼账号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="客户姓名" prop="customerName">
            <el-input
              v-model="queryParams.customerName"
              placeholder="请输入客户姓名"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="订单状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="请选择"  clearable >
              <el-option
                v-for="dict in dict.type.order_status"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="免息券类型" prop="mxType">
            <el-select v-model="queryParams.mxType" placeholder="请选择"  clearable >
              <el-option
                v-for="dict in dict.type.mx_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="预定抢购时间" prop="presetTime">
            <el-date-picker clearable
                            v-model="queryParams.presetTime"
                            type="date"
                            value-format="yyyy-MM-dd"
                            placeholder="选择预定抢购日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="所有者" prop="ownerUserId">
            <el-select v-model="queryParams.ownerUserId" placeholder="请选择" clearable size="small">
              <el-option
                v-for="dict in dict.type.ower_user"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>

          </el-form-item>
        </el-col>
      </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="预定抢购时间" prop="presetTimes">
              <el-date-picker
                class="custom-datepicker"
                v-model="queryParams.presetTimes"
                type="daterange"
                range-separator="至"
                value-format="yyyy-MM-dd"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>

            </el-form-item>
          </el-col>

            <el-col :span="8">
              <el-form-item label="来源" prop="mxSource">
                <el-select v-model="queryParams.mxSource" placeholder="请选择"  clearable >
                  <el-option
                    v-for="dict in dict.type.mx_source"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
      </el-row>
          <div style="text-align: center">
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </div>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['jd:order:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['jd:order:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['jd:order:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['jd:order:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="openRebateUrl"
        >获取返利链接</el-button>
      </el-col>
<!--      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>-->
      <el-button style="float: right;" icon="el-icon-refresh-right" size="mini" @click="refreshTodayCookieStatus" :loading="refreshLoading">刷新今日抢购登录状态</el-button>
    </el-row>

    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange" :row-class-name="tableRowClassName">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="商品名称" align="center" prop="goodsName" width="80"/>
      <el-table-column label="预定抢购时间" align="center" prop="presetTime" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.presetTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="京东账号" align="center" prop="jdAccount" :show-overflow-tooltip="true"/>
      <el-table-column label="cookie" align="center" prop="cookie" width="80">
        <template slot-scope="scope">
          <div slot="reference">
            <el-popover
              placement="top-start"
              title="用户cookie"
              width="500"
              trigger="hover"
              :content="scope.row.cookie">
              <el-button
                slot="reference"
                style="margin-left: 3px"
                type="success"
                icon="el-icon-document-copy"
                circle
                v-clipboard:copy="scope.row.cookie"
                v-clipboard:success="onCopySuccess"
                v-clipboard:error="onCopyError">
              </el-button>
            </el-popover>
          </div>
        </template>
      </el-table-column>
<!--      <el-table-column label="复制Cookie" align="center" prop="fishAccount" width="100">
        <template slot-scope="scope">
          <el-button style="margin-left: 3px" type="success" icon="el-icon-document-copy" circle v-clipboard:copy="scope.row.cookie" v-clipboard:success="onCopySuccess" v-clipboard:error="onCopyError"></el-button>
        </template>
      </el-table-column>-->
<!--      <el-table-column label="cookie登记时间" align="center" prop="cookieRecordTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.cookieRecordTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>-->
      <el-table-column label="闲鱼账号" align="center" prop="fishAccount" />
      <el-table-column label="免息券类型" align="center" prop="mxType" width="130">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.mx_type"
            :value="scope.row.mxType"
          >
          </dict-tag>
        </template>
      </el-table-column>
      <el-table-column label="来源" align="center" prop="mxSource"   width="100">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.mx_source"
            :value="scope.row.mxSource"
          >
          </dict-tag>
        </template>
      </el-table-column>
      <!--
      <el-table-column label="客户姓名" align="center" prop="customerName" />
      <el-table-column label="收货地址" align="center" prop="address" />
      <el-table-column label="电话" align="center" prop="phoneNumber" />-->

<!--      <el-table-column label="用户id" align="center" prop="createUserId" />
      <el-table-column label="单件商品原价" align="center" prop="goodsOriginalPrice" />
      <el-table-column label="单件商品现价" align="center" prop="goodsNowPrice" />
      <el-table-column label="商品数量" align="center" prop="goodsAmount" />
      <el-table-column label="订单总价" align="center" prop="orderPrice" />
      <el-table-column label="返现" align="center" prop="cashback" />
      <el-table-column label="订单实际收入" align="center" prop="realIncome" />-->
      <el-table-column label="商品链接" align="center" prop="goodsUrl" >
        <template slot-scope="scope">
          <el-popover
            placement="top-start"
            title="商品链接"
            width="400"
            trigger="hover"
            :content="scope.row.goodsUrl">
            <div class="inline-buttons" slot="reference">
              <el-button
                :disabled="scope.row.goodsUrl == null"
                style="margin-right: 3px"
                type="primary"
                icon="el-icon-paperclip"
                circle
                @click="redirectToGoodsUrl(scope.row.goodsUrl)">
              </el-button>
              <el-button
                :disabled="scope.row.goodsUrl == null"
                style="margin-left: 3px"
                type="success"
                icon="el-icon-document-copy"
                circle
                @click="getGoodsUrl(scope.row.goodsUrl)"
                v-clipboard:copy="tableGoodsUrl"
                v-clipboard:success="onCopySuccess"
                v-clipboard:error="onCopyError">
              </el-button>
            </div>
          </el-popover>
        </template>
<!--        <el-button :disabled="scope.row.goodsUrl ==null"
                   style="margin-left: 3px" type="success"
                   icon="el-icon-paperclip" circle
                   @click="redirectToGoodsUrl(scope.row.goodsUrl)">
        </el-button>-->
<!--        <template slot-scope="scope">
          <div slot="reference">
            <el-popover
              placement="top-start"
              title="商品链接"
              width="500"
              trigger="hover"
              :content="scope.row.goodsUrl">

            </el-popover>
          </div>

         </template>-->
      </el-table-column>
      <el-table-column label="归属" align="center" prop="ownerUserName" fixed="right"/>
      <el-table-column label="订单状态" align="center" prop="status" fixed="right">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.order_status"
            :value="scope.row.status"
          >
          </dict-tag>
          <el-button v-show="scope.row.status==='1'" type="success" icon="el-icon-check" circle  @click="completeOrder(scope.row,'5')" size="mini"></el-button>
          <el-button v-show="scope.row.status==='0'"  type="warning" icon="el-icon-star-off" circle  @click="completeOrder(scope.row,'1')" size="mini"></el-button>
        </template>
      </el-table-column>
      <el-table-column label="登陆状态" align="center" prop="loginStatus" fixed="right"  width="100">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.login_status"
            :value="scope.row.loginStatus"
          >
          </dict-tag>
        </template>
      </el-table-column>
      <el-table-column label="是否返利" align="center" prop="addRebate" fixed="right"  width="100">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.addRebate"
            active-color="#13ce66"
            active-value="1"
            inactive-value="0"
            @change="changeRebate(scope.row)"
           >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="180" >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-show="!showHistory"
          >修改</el-button>

          <el-popover
            placement="top"
            width="160"
            trigger="hover"
            v-show="!showHistory"
            >
            <p>选择用户</p>
            <div >
              <el-button
                v-for="user in dict.type.ower_user"
                :key="user.value"
                size="mini"
                type="text"
                @click="checkUser(user.value, scope.row)">
                {{ user.label }}
              </el-button>
             </div>
            <el-button slot="reference" size="mini" icon="el-icon-goods" type="text" v-hasPermi="['system:post:add']">归属</el-button>
          </el-popover>


          <el-button
            size="mini"
            type="text"
            icon="el-icon-refresh"
            @click="updateOrderLoginStatus(scope.row)"
            v-show="!showHistory"
          >登陆状态</el-button>
          <el-button
            size="mini"
            type="text"
            v-has-permi="['set_order_role']"
            @click="changeOrderRole(scope.row)"
            v-show="!showHistory"
          >{{scope.row.allShow==='1'?'设置权限':'全部可见'}}</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-s-unfold"
            @click="openCouponView(scope.row)"
            v-show="!showHistory"
          >优惠券列表
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-tickets"
            @click="handelOrderDetailOpen(scope.row)"
            v-show="!showHistory"
          >详细
          </el-button>
        </template>
      </el-table-column>
<!--      <el-table-column label="抢券" align="center" class-name="small-padding fixed-width" fixed="right" width="100">
        <template slot-scope="scope" v-show="scope.row.status==='0'">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="get12coupon(scope.row)"
          >12期</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-refresh"
            @click="get6coupon(scope.row)"
          >6期</el-button>
        </template>
      </el-table-column>-->
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改mx订单对话框 -->
    <el-dialog :title="title" :visible.sync="open" v-dialogFlex width="45%" append-to-body :close-on-click-modal="false" :before-close="cancel" >
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-row>
          <el-col :span="11">
            <el-form-item label="商品名称" prop="goodsName">
              <el-input v-model="form.goodsName" placeholder="请输入商品名称" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="免息券类型" prop="mxType">
              <el-select v-model="form.mxType" placeholder="请选择" clearable>
                <el-option
                  v-for="dict in dict.type.mx_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="11">
            <el-form-item label="预定抢购时间" prop="presetTime">
              <el-date-picker clearable
                              class="custom-datepicker"
                              v-model="form.presetTime"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择预定抢购时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="来源" prop="mxSource">
              <el-select v-model="form.mxSource" placeholder="请选择" clearable>
                <el-option
                  v-for="dict in dict.type.mx_source"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="京东账号" prop="jdAccount">
              <el-input v-model="form.jdAccount" placeholder="请输入京东账号" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="订单状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择" clearable>
                <el-option
                  v-for="dict in dict.type.order_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="spanWidth">
            <el-form-item label="用户cookie" prop="cookie">
              <el-input v-model="form.cookie" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
          <el-button style="margin-left: 3px" type="success" icon="el-icon-document-copy" circle v-clipboard:copy="form.cookie" v-clipboard:success="onCopySuccess" v-clipboard:error="onCopyError"></el-button>
        </el-row>
<!--        <el-row>
          <el-col :span="spanWidth">
            <el-form-item label="cookie登记时间" prop="cookieRecordTime">
              <el-date-picker clearable
                              v-model="form.cookieRecordTime"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择cookie登记时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>-->
        <el-row>
        <el-col :span="11">
          <el-form-item label="闲鱼账号" prop="fishAccount">
            <el-input v-model="form.fishAccount" placeholder="请输入闲鱼账号" />
          </el-form-item>
        </el-col>
          <el-col :span="11">
            <el-form-item label="客户姓名" prop="customerName">
              <el-input v-model="form.customerName" placeholder="请输入客户姓名" />
            </el-form-item>
          </el-col>
        </el-row>
         <el-row>
          <el-col :span="spanWidth">
            <el-form-item label="客户编号" prop="createUserId">
              <el-input v-model="form.createUserId" placeholder="请输入客户编号" />
              <el-button round @click="userOpen=true">选择用户</el-button>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="spanWidth">
            <el-form-item label="订单总价" prop="orderPrice">
              <el-input v-model="form.orderPrice" placeholder="请输入订单总价" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="spanWidth">
            <el-form-item label="商品链接" prop="goodsUrl">
              <el-input v-model="form.goodsUrl" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
          <el-button :disabled="form.goodsUrl ==null" style="margin-left: 3px" type="primary" icon="el-icon-paperclip" circle @click="redirectToGoodsUrl(form.goodsUrl)"></el-button>
          <el-button
            :disabled="form.goodsUrl == null"
            style="margin-left: 3px"
            type="success"
            icon="el-icon-document-copy"
            circle
            @click="getGoodsUrl(form.goodsUrl)"
            v-clipboard:copy="tableGoodsUrl"
            v-clipboard:success="onCopySuccess"
            v-clipboard:error="onCopyError">
          </el-button>
        </el-row>
<!--        <el-row>
          <el-col :span="spanWidth">
            <el-form-item label="返现" prop="cashback">
              <el-input v-model="form.cashback" placeholder="请输入返现" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="spanWidth">
            <el-form-item label="订单实际收入" prop="realIncome">
              <el-input v-model="form.realIncome" placeholder="请输入订单实际收入" />
            </el-form-item>
          </el-col>
        </el-row>-->
        <el-row v-show="form.goodsUrl != null">
          <el-col :span="spanWidth">
            <el-form-item label="返利链接" prop="rebateUrl">
              <el-input v-model="form.rebateUrl" type="textarea" placeholder="请输入返利链接" />
              <el-button icon="el-icon-sell" circle @click="getRebateUrl(form.goodsUrl)" style="position: absolute; right: 10px; top: 50%; transform: translateY(-50%);"></el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="spanWidth">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="align-center">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 添加或修改mx订单对话框 -->
    <el-dialog title="批量修改" :visible.sync="batchOpen" v-dialogFlex width="45%" append-to-body :close-on-click-modal="false" :before-close="cancel" >
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-row>
          <el-col :span="11">
            <el-form-item label="商品名称" prop="goodsName">
              <el-input v-model="form.goodsName" placeholder="请输入商品名称" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="免息券类型" prop="mxType">
              <el-select v-model="form.mxType" placeholder="请选择" clearable>
                <el-option
                  v-for="dict in dict.type.mx_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="11">
            <el-form-item label="预定抢购时间" prop="presetTime">
              <el-date-picker clearable
                              class="custom-datepicker"
                              v-model="form.presetTime"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择预定抢购时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="来源" prop="mxSource">
              <el-select v-model="form.mxSource" placeholder="请选择" clearable>
                <el-option
                  v-for="dict in dict.type.mx_source"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="订单状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择" clearable>
                <el-option
                  v-for="dict in dict.type.order_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row >
          <el-col :span="spanWidth">
            <el-form-item label="返利链接" prop="rebateUrl">
              <el-input v-model="form.rebateUrl" type="textarea" placeholder="请输入返利链接" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="align-center">
        <el-button type="primary" @click="batchUpdateOrder" v-loading="batchLoading">确 定</el-button>
        <el-button @click="cancelBatch">取 消</el-button>
      </div>
    </el-dialog>

<!--优惠券列表-->
    <coupon ref="coupon" :dialogVisible="couponOpen" @closeCoupon="closeCoupon"></coupon>
    <customerInfo ref="userInfo" :dialogVisible="userOpen" @chooseUser="chooseUser" @close="closeUserInfo"></customerInfo>
    <OrderDetail ref="OrderDetail" :open="orderDetailOpen"  @close="closeOrderDetail"></OrderDetail>
    <el-dialog title="归历史" :visible.sync="hisDialogOpen">
      <el-form :model="hisForm">
        <el-form-item label="归档范围:" :label-width="160">
          <el-date-picker
            v-model="hisForm.archiveTime"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :default-time="['00:00:00', '23:59:59']">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div class="text-center">
        <el-button @click="hisDialogOpen = false">取 消</el-button>
        <el-button type="primary" @click="toArchiveOrder">确 定</el-button>
      </div>
    </el-dialog>
    <get-rebate-url-vue :dialogVisible="rebateOpen" @close="closeRebateUrl"/>
  </div>
</template>

<script>
import {
  listOrder,
  getOrder,
  delOrder,
  addOrder,
  updateOrder,
  updateOrderLoginStatus, changeRebateStatus, refreshTodayCookieStatus, batchUpdate, listHisOrder, archiveOrder
} from '@/api/mx/order'
import  coupon from '@/views/components/couponView/index'
import  customerInfo from '@/views/components/customerSelect/customerSelect'
import OrderDetail from "@/views/mx/order/OrderDetail.vue";
import { getUser } from '@/api/system/user'
import { getCouponsBy12, getCouponsBy6 } from '@/api/jdInfo'
import getRebateUrlVue from '@/views/mx/order/components/getRebateUrl'
import { getRebateUrl } from '@/api/mx/order'
export default {
  dicts:['login_status','order_status','mx_type','ower_user','mx_source'],
  name: "order",
  components: {coupon,customerInfo,OrderDetail,getRebateUrlVue},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // mx订单表格数据
      orderList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        goodsName: null,
        goodsUrl: null,
        presetTime: null,
        jdAccount: null,
        cookie: null,
        cookieRecordTime: null,
        fishAccount: null,
        customerName: null,
        address: null,
        phoneNumber: null,
        mxType: null,
        status: null,
        createUserId: null,
        goodsOriginalPrice: null,
        goodsNowPrice: null,
        goodsAmount: null,
        orderPrice: null,
        cashback: null,
        realIncome: null,
        presetTimes: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        createTime: [
          { required: true, message: '下单时间不能为空', trigger: 'blur' }
        ]
      },
      spanWidth: 20,
      couponOpen: false,//优惠券弹窗
      userOpen: false,//用户弹窗

      couponList: null,
      ownerUserName: null,//订单归属人姓名
      tableGoodsUrl: null,//表格商品链接
      orderDetailOpen: false,//订单详细界面
      refreshLoading: false,//刷新今日cookie状态按钮加载
      batchOpen: false,//批量修改
      batchLoading: false,//批量更新加载
      showHistory: false,//显示历史
      hisDialogOpen:false,//归历史弹窗
      hisForm:{archiveTime:null},//历史表单
      rebateOpen:false,// 返利窗口
    }
  },
  created() {
    this.getList();
  },
  methods: {
    /**
     * 更新页面
     */
    refresh(){
      location.reload()
    },
    /** 查询mx订单列表 */
    getList() {
      let needReload = this.$route.query.needReload
      if (needReload != null || needReload != undefined) {
       this.$router.push("/mx/order")
        location.reload();
      }
      this.loading = true;

      if (this.showHistory) {
        //显示历史
        listHisOrder(this.queryParams).then(response => {
          this.orderList = response.rows
          this.total = response.total
          this.loading = false
        })
      } else {
        //订单
        listOrder(this.queryParams).then(response => {
          this.orderList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      }

    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    cancelBatch() {
      this.batchOpen = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        goodsName: null,
        goodsUrl: null,
        presetTime: null,
        jdAccount: null,
        cookie: null,
        cookieRecordTime: null,
        createTime: null,
        fishAccount: null,
        customerName: null,
        address: null,
        phoneNumber: null,
        mxType: null,
        status: null,
        createUserId: null,
        goodsOriginalPrice: null,
        goodsNowPrice: null,
        goodsAmount: null,
        orderPrice: null,
        cashback: null,
        realIncome: null,
        remark: null,
        presetTimes: null,
        rebateUrl: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length <1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加mx订单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      if (this.ids.length > 1) {
        this.form = {}
        this.batchOpen = true
      } else {
        getOrder(id).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改mx订单";
        });
      }

    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateOrder(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addOrder(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /**
     * 批量更新订单
     */
    batchUpdateOrder() {
      let batchIds = this.ids
      this.form.batchIds = batchIds
      this.batchLoading = true
      batchUpdate(this.form).then(res=>{
        if (res.code === 200) {

          this.$message.success('操作成功')
          this.form = {}
          this.batchLoading = false
          this.batchOpen = false
          this.getList()
        }
      }).catch(()=>{
        this.batchLoading = false
      })
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除mx订单编号为"' + ids + '"的数据项？').then(function() {
        return delOrder(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('jd/order/export', {
        ...this.queryParams
      }, `order_${new Date().getTime()}.xlsx`)
    },
    /** 复制情况 **/
    onCopySuccess(){
      this.$message.success('复制成功')
    },
    onCopyError(){
      this.$message.error('复制失败')
    },

    /**
     * 查看免息券
     */
    openCouponView(row){
      this.couponOpen = true
      this.$refs.coupon.getCoupon(row)
    },
    closeCoupon(){
      this.couponOpen = false
      /* this.couponList = null */
    },
    /**
     * 获取最新登陆状态
     * @param row
     */
    updateOrderLoginStatus(row){
      updateOrderLoginStatus(row).then(response => {
        if (response.code === 200) {
          this.$message.success("获取成功")
          this.getList();
        }
      });
    },
    /**
     * 用户界面选择用户
     */
    chooseUser(user){
      //选择成功
      this.$message.success("选择成功")
      this.form.createUserId = user.customerId
      this.userOpen=false
    },
    /**
     * 关闭用户列表
     */
    closeUserInfo(){
      this.userOpen=false
    },
    /**
     * 更新订单归属用户
     */
    checkUser(ownUserId, row) {
      let data = {
        id: row.id,
        ownerUserId: ownUserId
      }
      updateOrder(data).then(response => {
        if (response.code === 200) {
          this.$modal.msgSuccess('修改成功')
          this.open = false
          this.getList()
        }

      })
    },

    /**
     * 根据用户名获取用户id
     * @param userId
     */
    getUserName(userId){
      if (userId === undefined || userId == null) {
        this.$message.error("没有归属人信息")
        return

      }
      getUser(userId).then(res=>{
        if (res.code === 200) {
          this.ownerUserName =res.data.nickName
        }else {
          this.$message.error("获取失败")
          this.ownerUserName = null
        }
      })
    },
    /**
     * 完成订单
     */
    completeOrder(data,status) {
      let params = {
        id: data.id,
        status: status
      }
      updateOrder(params).then(response => {
        this.$modal.msgSuccess('操作成功')
        this.open = false
        this.getList()
      })
    },
    /**
     * 获取12期免息券
     * @param row
     */
    get12coupon(row) {
      console.log(row)
      getCouponsBy12(row).then(res => {
        if (res.code === 200) {
          let reultMsg = res.data.subCodeMsg
          this.$message.success(reultMsg)
        }
      })
    },
    get6coupon(row) {
      console.log(row)
      getCouponsBy6(row).then(res => {
        if (res.code === 200) {
          let reultMsg = res.data.subCodeMsg
          this.$message.success(reultMsg)
        }
      })
    },
    /**
     * 改变返利状态
     */
    changeRebate(row) {
      changeRebateStatus(row).then(res => {
        if (res.code === 200) {
          this.$message.success("修改成功");
          this.getList();
        } else {
          this.getList();
        }
      })
    },
    /**
     * 跳转链接
     */
    // 新增的方法，用于处理点击事件并跳转
    redirectToGoodsUrl(url) {
      let linkRegex = /(https?:\/\/[^\s]+)/g;
      if (url && url !== '') {
        let jdUrl = url.match(linkRegex);
        window.open(jdUrl, '_blank');
      } else {
        alert('请先输入商品链接!');
      }
    },
    /**
     * 获取商品链接
     * @param url
     */
    getGoodsUrl(url) {
      let linkRegex = /(https?:\/\/[^\s]+)/g;
      if (url && url !== '') {
        let jdUrl = url.match(linkRegex);
        this.tableGoodsUrl= jdUrl
      } else {
       this.$message.error("未获取到商品链接")
      }
    },
    /**
     * 表格颜色
     * @param row
     * @param rowIndex
     * @returns {string}
     */
    tableRowClassName({row, rowIndex}) {
      const today = new Date();
      const year = today.getFullYear();
      let month = today.getMonth() + 1;
      month = month < 10 ? '0' + month : month; // 补零
      let day = today.getDate();
      day = day < 10 ? '0' + day : day; // 补零
      let currentDate = `${year}-${month}-${day}`;
      if (currentDate === row.presetTime && (row.rebateUrl == null || row.rebateUrl === '') ) {
        return 'warning-row';
      } else {
        return '';
      }

    },
    /**
     * 打开订单详细
     */
    handelOrderDetailOpen(row){

      this.orderDetailOpen =true;
      this.$refs.OrderDetail.getOrderDetail(row.id);

    },
    /**
     * 关闭订单详细
     */
    closeOrderDetail(){
      this.orderDetailOpen =false;
    },
    /**
     * 刷新今日cookie状态
     */
    refreshTodayCookieStatus(){
      this.refreshLoading =true
      refreshTodayCookieStatus().then(res=>{
        if (res.code == 200) {
          this.$message.success("刷新成功");
          this.refreshLoading =false
          this.queryParams.presetTime = this.parseTime(new Date(), '{y}-{m}-{d}');
          this.getList();
        }
      }).final(()=>{
        this.refreshLoading =false
      })
    },
    formatDate(date, format) {
      const map = {
        y: date.getFullYear(),
        m: ('0' + (date.getMonth() + 1)).slice(-2),
        d: ('0' + date.getDate()).slice(-2)
      };
      return format.replace(/y+|m+|d+/g, (match) => map[match[0]]);
    },
    /**
     * 打开订单归历史界面
     */
    openArchiverOrder(){
      this.hisForm = {}
      this.hisDialogOpen = true
    },
    /**
     * 订单归历史
     */
    toArchiveOrder(){
      //console.log(this.hisForm)
      if (this.hisForm.archiveTime) {
        let data= this.hisForm.archiveTime

        archiveOrder(data).then(res=>{
          if (res.code === 200) {
            this.$message.success("归历史成功")
            this.hisDialogOpen = false
          }
        })
      }else {
        this.$message.error("请选择时间")
      }
    },
    /**
     * 改变订单权限
     * @param row
     */
    changeOrderRole(row) {
      const data = {
        id: row.id,
        allShow: row.allShow === '1' ? '0' : '1' // 切换 allShow 的值
      };

      updateOrder(data).then(response => {
        if (response.code === 200) {
          this.$message.success("修改成功");
          this.getList(); // 刷新列表
        } else {
          this.$message.error("修改失败");
        }
      }).catch(() => {
        this.$message.error("修改失败");
      });
    },
    /**
     * 打开转链窗口
     */
    openRebateUrl(){
      this.rebateOpen =true
    },
    closeRebateUrl(){
      this.rebateOpen =false
    },
    getRebateUrl(goodsUrl) {
      // 这里可以添加保存逻辑，比如调用后端API保存返利链接
      const data = {
        goodsUrl: goodsUrl,
      };
      // 假设有一个 saveRebateUrl 的 API
      getRebateUrl(data).then(response => {
        if (response.code == 200) {
          this.$set(this.form, 'rebateUrl', response.data.clickURL)
          // this.rebateUrl = response.data.clickURL
          this.$message.success('获取成功');
          this.$forceUpdate()
        }
      }).catch(() => {
        this.$message.error('获取失败');
      });
    }
  }
};
</script>

<style scoped>
.table2  {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
}
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 30%;
}
.inline-buttons {
  display: flex;
  align-items: center;
}
.inline-buttons > el-button:not(:first-child) {
  margin-left: 3px;
}
.custom-datepicker {
  width: 100%;
  max-width: 250px; /* 根据实际情况调整 */
}
</style>
<style>
.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}
</style>
